// 分页组件

<template>
  <div class="xtx-pagination" v-if="total>0">
    <a href="javascript:;" class="disabled" v-if="myCurrpage<=1">上一页</a>
    <a href="javascript:;" v-else @click="changePage(myCurrpage-1)">上一页</a>

    <span v-if="page.start>1">...</span>
    <a href="javascript:;" :class="{active:myCurrpage===i}" v-for="i in pager.btnArr" :key="i" @click="changePage(i)">{{i}}</a>
    <!-- <a href="javascript:;">4</a>
    <a href="javascript:;">5</a>
    <a href="javascript:;">6</a>
    <a href="javascript:;">7</a> -->
    <!-- <span>...</span> -->
    <span v-if="pager.end<pager.pageCount">...</span>
    <a v-if="myCurrPage>=pager.pageCount" href="javascript:;" class="disabled">下一页</a>
    <a v-else href="javascript:;" @click="changePage(myCurrpage+1)">下一页</a>
  </div>
</template>

<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',

  props: {
    total: {
      type: Number,
      default: 100
    },
    currentPage: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    }
  },

  setup (props, { emit }) {
    const myTotal = ref(100)

    const myPageSize = ref(10)

    const myCurrPage = ref(1)

    const btnCount = 5

    const pager = computed(() => {
      // 总页数
      const pageCount = Math.ceil(myTotal.value / myPageSize.value)

      // 让当前选中的按钮处于中间位置

      let start = myCurrPage.value - Math.floor(btnCount / 2)

      let end = start + btnCount - 1

      // 判断start和end是否越界

      if (start < 1) {
        start = 1
        end = (start + btnCount - 1) > pageCount ? pageCount : (start + btnCount - 1)
      }

      if (end > pageCount) {
        end = pageCount
        start = (end - btnCount + 1) < 1 ? 1 : (end - btnCount + 1)
      }

      // 处理完毕start和end得到按钮数组
      const btnArr = []
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      return { pageCount, start, end, btnArr }
    })

    const changePage = (newPage) => {
      if (myCurrPage.value !== newPage) {
        myCurrPage.value = newPage
        // 通知父组件最新页码
        emit('current-change', newPage)
      }
    }

    watch(props, () => {
      myTotal.value = props.total
      myCurrPage.value = props.currentPage
      myPageSize.value = props.pageSize
    }, { immediate: true })

    return { pager, myCurrPage, changePage }
  }
}
</script>

<style lang="less" scoped>
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
